package org.TCC_NOVO.client.visual;

import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.Function;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.IntegerFieldDef;
import com.gwtext.client.data.ObjectFieldDef;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.Tool;
import com.gwtext.client.widgets.Toolbar;
import com.gwtext.client.widgets.ToolbarButton;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.event.GridCellListenerAdapter;
import java.util.ArrayList;
import java.util.List;
import org.TCC_NOVO.client.GWTServiceAsync;
import org.TCC_NOVO.client.modelo.Usuario;

public class UsuariosPanel extends Panel {

    private final GWTServiceAsync controller;

    private UsuariosPanel self;
    private UsuariosForm UsuaForm;
    //PapeisForm PapeisForm;
    private Store store;
    private GridPanel grid;
    private RecordDef recordDef;
    private Toolbar toolbar;
    private List<Usuario> usuarios = new ArrayList();

    public Store getStore() {
        return store;
    }

    

    public UsuariosPanel(GWTServiceAsync controller) {
        this.controller = controller;
        this.self = this;
        this.init();        
    }

    private void carregarDados(List<Usuario> result){
        usuarios = result;
        for (int i = 0; i < result.size(); ++i) {
            addRecord(result.get(i));
        }        
    }

    private void init(){
        this.setBorder(true);
        this.setPaddings(2);
        this.UsuaForm = new UsuariosForm(this, controller);
        
        recordDef = new RecordDef(new FieldDef[]{
            new IntegerFieldDef("ID"),
            new StringFieldDef("Nick"),
            new StringFieldDef("Senha"),
            new StringFieldDef("SenhaConfig"),
            new StringFieldDef("Nome"),            
            new StringFieldDef("Email"),
            new ObjectFieldDef("Papel"),
        });
        
        store = new Store(recordDef);
        grid = new GridPanel();
        grid.setStore(store);        

        ColumnConfig[] columns = new ColumnConfig[]{
            new ColumnConfig("Nick", "Nick", 70, true),
            new ColumnConfig("Nome", "Nome", 160, true),            
            new ColumnConfig("Email", "Email", 160, true),
            new ColumnConfig("Papel", "Papel", 160, true),            
        };

        ColumnModel columnModel = new ColumnModel(columns);
        grid.setColumnModel(columnModel);
        grid.setFrame(true);
        grid.setStripeRows(true);
        grid.setSize(1020, 600);
        grid.setTitle("Usuários");
        grid.addTool(new Tool(Tool.REFRESH, new Function() {
            @Override
            public void execute() {
                grid.getEl().mask("Carregando", "x-mask-loading");
                carregarGrid();
                Timer timer = new Timer() {
                    @Override
                    public void run() {
                        grid.getEl().unmask();
                    }
                };
                timer.schedule(1000);
            }
        }, "Atualizar"));        

        grid.addGridCellListener(new GridCellListenerAdapter(){
            @Override
            public void onCellDblClick(GridPanel grid, int rowIndex, int colIndex, EventObject e){
                UsuaForm.IDForm = grid.getSelectionModel().getSelected().getAsInteger("ID");
                UsuaForm.show(true);
                UsuaForm.loadRecord(grid.getSelectionModel().getSelected());
            }
        });

        toolbar = getToolbar();

        toolbar.setSize(grid.getWidth(), 25);
        this.add(toolbar);
        this.add(grid);
        
        carregarGrid();
    }

    public void carregarGrid(){
        store.removeAll();
        controller.retornarDadosUsuarios(null, new CallBackRetUsuario());
    }
       
    private class CallBackRetUsuario implements AsyncCallback<List<Usuario>> {
        @Override
	public void onFailure(Throwable e) {
		MessageBox.alert("Erro ao carregar dados... ", e.getMessage());
	}
        @Override
	public void onSuccess(List<Usuario> result) {
            carregarDados(result);
        }
    }

   
    private void removeUsuarios(){
        store.remove(grid.getSelectionModel().getSelected());
    }

    public void addRecord(Usuario Usua){
        Object[] rowData = new Object[]{
          Usua.getId(),
          Usua.getNick(),
          Usua.getSenha(),
          Usua.getSenha(),
          Usua.getNome(),
          Usua.getEmail(),
          Usua.getPapel()
        };
        Record record = recordDef.createRecord(rowData[0].toString(), rowData);
        store.add(record);
    }

    public Toolbar getToolbar(){

        final AsyncCallback callbackExcluirReg = new AsyncCallback() {
            @Override
            public void onSuccess(Object result) {
                //MessageBox.alert("Registro Gravado com Sucesso!");
            }
            @Override
            public void onFailure(Throwable caught) {
               MessageBox.alert("Erro ", caught.getMessage()); }
        };

        ToolbarButton btnNovo = new ToolbarButton();
        btnNovo.setText(" Incluir");
        btnNovo.setIcon("Images/filenew.png");
        btnNovo.setTooltip("Incluir um novo registro");
        btnNovo.addListener(new ButtonListenerAdapter(){
            @Override
            public void onClick(Button button, EventObject e){
                UsuaForm.show(false);
                Object[] rowData = new Object[]{"","","","","","",null};
                Record record = recordDef.createRecord(rowData[0].toString(), rowData);
                UsuaForm.loadRecord(record);
            }
        });
        
        ToolbarButton btnEdit = new ToolbarButton();
        btnEdit.setText(" Editar");
        btnEdit.setIcon("Images/edit.png");
        btnEdit.setTooltip("Edita o registro selecionado");
        btnEdit.addListener(new ButtonListenerAdapter(){
            public void onClick(Button button, EventObject e){
                if (grid.getSelectionModel().getSelected() == null){
                    MessageBox.alert("Necessário Selecionar Algum Registro! ");                    
                }else{
                    UsuaForm.IDForm = grid.getSelectionModel().getSelected().getAsInteger("ID");
                    UsuaForm.show(true);
                    UsuaForm.loadRecord(grid.getSelectionModel().getSelected());
                }
            }
        });

        ToolbarButton btnRemove = new ToolbarButton();
        btnRemove.setText(" Remover");
        btnRemove.setIcon("Images/remove.png");
        btnRemove.setTooltip("Remove o registro selecionado");
        btnRemove.addListener(new ButtonListenerAdapter(){
            public void onClick(Button button, EventObject e){
                if (grid.getSelectionModel().getSelected() == null){
                    MessageBox.alert("Necessário Selecionar Algum Registro! ");
                }else {
                    MessageBox.confirm("Confirmação de Exclusão", "Deseja Realmente Excluir o Registro?", new MessageBox.ConfirmCallback(){
                    public void execute(String btnID){
                        if (btnID.equals("yes")){
                                //Remoção do Registro no Servidor (Banco de Dados)...
                                controller.excluirUsuario(grid.getSelectionModel().getSelected().getAsString("Nick"), callbackExcluirReg);
                                //Remoção do Registro no Cliente (Grid)...
                                removeUsuarios();
                        }
                    }});
                }    
            }
        });

        Toolbar toobar = new Toolbar();
        toobar.addButton(btnNovo);
        toobar.addButton(btnEdit);
        toobar.addButton(btnRemove);
        toobar.addSeparator();

        return toobar;
    }

}
